-- jianmu.lua
-- 定义建木的预制体和相关逻辑
local JIANMU_SAPLING = TUNING.ENTITY_LIST.JIANMU_SAPLING
local JIANMU = TUNING.ENTITY_LIST.JIANMU

local assets = {
    Asset("ANIM", JIANMU.anim),  -- 动画资源
    Asset("IMAGE", "images/map_icons/i26_jianmu.tex"),  -- 地图ICON
    Asset("ATLAS", "images/map_icons/i26_jianmu.xml"),  -- 地图ICON
}

local prefabs = {
    JIANMU_SAPLING.id, -- 锤子摧毁后的掉落物
}

-- 删除发光效果
local function RemoveGlowEffect(inst)
    if inst.light ~= nil then
        inst.light:Remove()
        inst.light = nil
    end
end

-- 添加发光效果
local function AddGlowEffect(inst)
    RemoveGlowEffect(inst)
    inst.light = SpawnPrefab("minerhatlight")
    if inst.light then
        inst.light.entity:SetParent(inst.entity)
        inst.light.Light:SetRadius(TUNING.JIANMU_CONFIG.GLOW_EFFECT_RADIUS)
        inst.light.Light:SetColour(1, 1, 0.8)
        inst.light.Light:SetIntensity(0.8) -- 设置光的强度
        inst.light.Light:SetFalloff(1)     -- 设置光的衰减，值越小衰减越慢
    end

    -- 监听世界时间变化事件
    local function UpdateLight()
        if inst.light ~= nil and inst.light:IsValid() then
            if TheWorld.state.isnight then
                inst.light.Light:Enable(true)
            else
                inst.light.Light:Enable(false)
            end
        end
    end

    -- 初始化时更新光源状态
    UpdateLight()

    -- 监听时间变化事件
    inst:WatchWorldState("isnight", UpdateLight)
    inst:WatchWorldState("isdusk", UpdateLight)
    inst:WatchWorldState("isday", UpdateLight)
end


-- 被锤子摧毁时的回调函数
local function OnHammered(inst, worker)
    local sapling = inst.components.lootdropper:SpawnLootPrefab(JIANMU_SAPLING.id)
    if sapling and sapling.components.i26_jianmu_data then
        inst.components.i26_jianmu_data:OnDestroy() -- 移除所有特效和任务
        sapling.components.i26_jianmu_data:OnLoad(inst.components.i26_jianmu_data:OnSave())
    end
    RemoveGlowEffect(inst)
    inst:Remove()
end

-- 检查是否可以接收的物品
local function AcceptTest_tt(inst, item, giver)
    if not TUNING.JIANMU_CONFIG.ENABLED_JIANMU then
        return false
    end
    if inst.components.i26_jianmu_data then
        return inst.components.i26_jianmu_data:CanAcceptItem(inst, item, giver)
    end
end

-- 检查时发送特效进度到聊天栏
local function AnnounceStatus(inst)
    if not TUNING.JIANMU_CONFIG.ENABLED_JIANMU then
        return
    end
    local lang = TUNING.LANGUAGE
    local enabledFlag = false
    if inst.components.i26_jianmu_data then
        local effects = inst.components.i26_jianmu_data.effects
        local messages = {}
        for effect_name, effect_data in pairs(effects) do
            local progress_info = {}
            for material_name, material_data in pairs(effect_data.materials) do
                -- 检查并设置默认值
                local material_display_name = TUNING.JIANMU_BUFF[lang][material_name] or material_name
                table.insert(progress_info,
                    string.format("%s: %d/%d", material_display_name, material_data.progress, material_data.required))
            end
            -- 检查并设置默认值
            if TUNING.JIANMU_BUFF[effect_name] or TUNING.JIANMU_BUFF[effect_name] == nil then
                enabledFlag = true
                local effect_display_name = TUNING.JIANMU_BUFF[lang][effect_name] or effect_name
                local message = string.format("%s: %s", effect_display_name, table.concat(progress_info, ", "))
                table.insert(messages, message)
            end
        end
        if enabledFlag then
            local full_message = table.concat(messages, " | ")
            TheNet:Announce(full_message)
        end
    end
end

-- 接受物品时更新特效进度, 并移除物品
local function OnAccept_tt(inst, giver, item)
    if inst.components.i26_jianmu_data then
        local isUpdateEffectProgress = inst.components.i26_jianmu_data:UpdateEffectProgress(inst, giver, item)
        if isUpdateEffectProgress then
            item:Remove()
        else
            giver.components.inventory:GiveItem(item, nil, inst:GetPosition())
        end
    end
end

-- 建木的预制体函数
local function jianmu_fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddMiniMapEntity()
    inst.entity:AddNetwork()

    inst.AnimState:SetBank(JIANMU.id)
    inst.AnimState:SetBuild(JIANMU.scmlName)
    inst.AnimState:PlayAnimation("idle2")

    MakeObstaclePhysics(inst, 2)

    inst:AddTag("i26_jianmu")
    inst:AddTag("tornado_nosucky") --mod兼容：永不妥协。不会被龙卷风刮走
    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    -- 添加 talker 组件
    inst:AddComponent("talker")
    inst:AddComponent("inspectable")

    inst:AddComponent("lootdropper")
    -- 添加i26_jianmu_data 组件
    inst:AddComponent("i26_jianmu_data")
    inst.components.i26_jianmu_data.is_sapling = false -- 确保不是树苗

    inst:AddComponent("workable")
    inst.components.workable:SetWorkAction(ACTIONS.HAMMER)
    inst.components.workable:SetWorkLeft(4)
    inst.components.workable:SetOnFinishCallback(OnHammered)

    -- 检查时发送特效进度到聊天栏
    inst.components.inspectable.getstatus = AnnounceStatus
    -- 交易组件
    inst:AddComponent("trader")
    inst.components.trader.deleteitemonaccept = false
    inst.components.trader.acceptnontradable = true
    inst.components.trader:SetAcceptTest(AcceptTest_tt)
    inst.components.trader.onaccept = OnAccept_tt
    -- 添加作物保护组件，防止作物枯萎
    inst:AddComponent("wateryprotection")
    inst.components.wateryprotection.extinguishheatpercent = TUNING.FIRESUPPRESSOR_EXTINGUISH_HEAT_PERCENT
    inst.components.wateryprotection.temperaturereduction = TUNING.FIRESUPPRESSOR_TEMP_REDUCTION
    inst.components.wateryprotection.witherprotectiontime = TUNING.FIRESUPPRESSOR_PROTECTION_TIME
    --inst.components.wateryprotection.addcoldness = TUNING.FIRESUPPRESSOR_ADD_COLDNESS
    inst.components.wateryprotection:AddIgnoreTag("player")

    AddGlowEffect(inst)

    return inst
end

return Prefab(JIANMU.id, jianmu_fn, assets, prefabs)
